package com.buydeem.custom;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author zengchao
 * @date 2022-03-10 20:15:55
 */
public class PackageImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //获取注解上的属性
        Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(PackageScan.class.getName());
        //扫描包
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        //添加过滤器扫描含有注解CustomInjection的类
        provider.addIncludeFilter(new AnnotationTypeFilter(CustomInjection.class));
        //扫描包下的BeanDefinition
        String[] basePackages = (String[]) attributes.get("basePackages");
        Set<BeanDefinition> candidateComponents = new LinkedHashSet<>();
        for (String basePackage : basePackages) {
            Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
            candidateComponents.addAll(components);
        }
        //注册BeanDefinition
        for (BeanDefinition component : candidateComponents) {
            beanDefinitionRegistry.registerBeanDefinition(component.getBeanClassName(),component);
        }
    }
}
